home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.006 / xemacs-1 / lib / xemacs-19.13 / lisp / modes / cmacexp.el < prev    next >
Encoding:
Text File  |  1995-03-25  |  12.5 KB  |  346 lines

  1. ;;; cmacexp.el --- expand C macros in a region
  2.  
  3. ;; Copyright (C) 1992, 1994 Free Software Foundation, Inc.
  4.  
  5. ;; Author: Francesco Potorti` <pot@cnuce.cnr.it>
  6. ;; Version: cmacexp.el,v 1.18 1994/09/05 04:33:23 rms Exp 
  7. ;; Adapted-By: ESR
  8. ;; Keywords: c
  9.  
  10. ;; This file is part of XEmacs.
  11.  
  12. ;; XEmacs is free software; you can redistribute it and/or modify it
  13. ;; under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation; either version 2, or (at your option)
  15. ;; any later version.
  16.  
  17. ;; XEmacs is distributed in the hope that it will be useful, but
  18. ;; WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  20. ;; General Public License for more details.
  21.  
  22. ;; You should have received a copy of the GNU General Public License
  23. ;; along with XEmacs; see the file COPYING.  If not, write to the Free
  24. ;; Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  25.  
  26. ;;; Synched up with: FSF 19.28.
  27.  
  28. ;; USAGE =============================================================
  29.  
  30. ;; In C mode C-C C-e is bound to c-macro-expand.  The result of the
  31. ;; expansion is put in a separate buffer.  A user option allows the
  32. ;; window displaying the buffer to be optimally sized.
  33. ;;
  34. ;; When called with a C-u prefix, c-macro-expand replaces the selected
  35. ;; region with the expansion.  Both the preprocessor name and the
  36. ;; initial flag can be set by the user.  If c-macro-prompt-flag is set
  37. ;; to a non-nil value the user is offered to change the options to the
  38. ;; preprocessor each time c-macro-expand is invoked.  Preprocessor
  39. ;; arguments default to the last ones entered.  If c-macro-prompt-flag
  40. ;; is nil, one must use M-x set-variable to set a different value for
  41. ;; c-macro-cppflags.
  42.  
  43. ;; A c-macro-expansion function is provided for non-interactive use.
  44.  
  45. ;; INSTALLATION ======================================================
  46.  
  47. ;; Put the following in your ~/.emacs file.
  48.  
  49. ;; If you want the *Macroexpansion* window to be not higher than
  50. ;; necessary: 
  51. ;;(setq c-macro-shrink-window-flag t)
  52. ;;
  53. ;; If you use a preprocessor other than /lib/cpp (be careful to set a
  54. ;; -C option or equivalent in order to make the preprocessor not to
  55. ;; strip the comments):
  56. ;;(setq c-macro-preprocessor "gpp -C")
  57. ;;
  58. ;; If you often use a particular set of flags:
  59. ;;(setq c-macro-cppflags "-I /usr/include/local -DDEBUG"
  60. ;;
  61. ;; If you want the "Preprocessor arguments: " prompt:
  62. ;;(setq c-macro-prompt-flag t)
  63.  
  64. ;; BUG REPORTS =======================================================
  65.  
  66. ;; Please report bugs, suggestions, complaints and so on to
  67. ;; pot@cnuce.cnr.it (Francesco Potorti`).
  68.  
  69. ;; IMPROVEMENTS OVER emacs 18.xx cmacexp.el ==========================
  70.  
  71. ;; - A lot of user and programmer visible changes.  See above.
  72. ;; - #line directives are inserted, so __LINE__ and __FILE__ are
  73. ;;   correctly expanded.  Works even with START inside a string, a
  74. ;;   comment or a region #ifdef'd away by cpp. cpp is invoked with -C,
  75. ;;   making comments visible in the expansion.
  76. ;; - All work is done in core memory, no need for temporary files.
  77.  
  78. ;; ACKNOWLEDGEMENTS ==================================================
  79.  
  80. ;; A lot of thanks to Don Maszle who did a great work of testing, bug
  81. ;; reporting and suggestion of new features.  This work has been
  82. ;; partially inspired by Don Maszle and Jonathan Segal's.
  83.  
  84. ;; BUGS ==============================================================
  85.  
  86. ;; If the start point of the region is inside a macro definition the
  87. ;; macro expansion is often inaccurate.
  88.  
  89.  
  90. (provide 'cmacexp)
  91.  
  92. (defvar c-macro-shrink-window-flag nil
  93.   "*Non-nil means shrink the *Macroexpansion* window to fit its contents.")
  94.  
  95. (defvar c-macro-prompt-flag nil
  96.   "*Non-nil makes `c-macro-expand' prompt for preprocessor arguments.")
  97.  
  98. (defvar c-macro-preprocessor "/lib/cpp -C"
  99.   "The preprocessor used by the cmacexp package.
  100.  
  101. If you change this, be sure to preserve the `-C' (don't strip comments)
  102. option, or to set an equivalent one.")
  103.  
  104. (defvar c-macro-cppflags ""
  105.   "*Preprocessor flags used by `c-macro-expand'.")
  106.  
  107. (defconst c-macro-buffer-name "*Macroexpansion*")
  108.  
  109. ;;;###autoload
  110. (defun c-macro-expand (start end subst)
  111.   "Expand C macros in the region, using the C preprocessor.
  112. Normally display output in temp buffer, but
  113. prefix arg means replace the region with it.
  114.  
  115. `c-macro-preprocessor' specifies the preprocessor to use.
  116. Prompt for arguments to the preprocessor \(e.g. `-DDEBUG -I ./include')
  117. if the user option `c-macro-prompt-flag' is non-nil.
  118.  
  119. Noninteractive args are START, END, SUBST.
  120. For use inside Lisp programs, see also `c-macro-expansion'."
  121.  
  122.   (interactive "r\nP")
  123.   (let ((inbuf (current-buffer))
  124.     (displaybuf (if subst
  125.             (get-buffer c-macro-buffer-name)
  126.               (get-buffer-create c-macro-buffer-name)))
  127.     (expansion ""))
  128.     ;; Build the command string.
  129.     (if c-macro-prompt-flag
  130.     (setq c-macro-cppflags
  131.           (read-string "Preprocessor arguments: "
  132.                c-macro-cppflags)))
  133.     ;; Decide where to display output.
  134.     (if (and subst
  135.          (and buffer-read-only (not inhibit-read-only))
  136.          (not (eq inbuf displaybuf)))
  137.     (progn
  138.       (message
  139.        "Buffer is read only: displaying expansion in alternate window")
  140.       (sit-for 2)
  141.       (setq subst nil)
  142.       (or displaybuf
  143.           (setq displaybuf (get-buffer-create c-macro-buffer-name)))))
  144.     ;; Expand the macro and output it.
  145.     (setq expansion (c-macro-expansion start end
  146.                        (concat c-macro-preprocessor " "
  147.                            c-macro-cppflags) t))
  148.     (if subst
  149.     (let ((exchange (= (point) start)))
  150.       (delete-region start end)
  151.       (insert expansion)
  152.       (if exchange
  153.           (exchange-point-and-mark)))
  154.       (set-buffer displaybuf)
  155.       (setq buffer-read-only nil)
  156.       (buffer-disable-undo displaybuf)
  157.       (erase-buffer)
  158.       (insert expansion)
  159.       (set-buffer-modified-p nil)
  160.       (if (string= "" expansion)
  161.       (message "Null expansion")
  162.     (c-macro-display-buffer))
  163.       (setq buffer-read-only t)
  164.       (setq buffer-auto-save-file-name nil)
  165.       (bury-buffer displaybuf))))
  166.  
  167.  
  168. ;; Display the current buffer in a window which is either just large
  169. ;; enough to contain the entire buffer, or half the size of the
  170. ;; screen, whichever is smaller.  Do not select the new
  171. ;; window.
  172. ;;
  173. ;; Several factors influence window resizing so that the window is
  174. ;; sized optimally if it is created anew, and so that it is messed
  175. ;; with minimally if it has been created by the user.  If the window
  176. ;; chosen for display exists already but contains something else, the
  177. ;; window is not re-sized.  If the window already contains the current
  178. ;; buffer, it is never shrunk, but possibly expanded.  Finally, if the
  179. ;; variable c-macro-shrink-window-flag is nil the window size is *never*
  180. ;; changed.
  181. (defun c-macro-display-buffer ()
  182.   (goto-char (point-min))
  183.   (c-mode)
  184.   (let ((oldwinheight (window-height))
  185.     (alreadythere            ;the window was already there
  186.      (get-buffer-window (current-buffer)))
  187.     (popped nil))            ;the window popped changing the layout 
  188.     (or alreadythere
  189.     (progn
  190.       (display-buffer (current-buffer) t)
  191.       (setq popped (/= oldwinheight (window-height)))))
  192.     (if (and c-macro-shrink-window-flag    ;user wants fancy shrinking :\)
  193.          (or alreadythere popped))
  194.     ;; Enlarge up to half screen, or shrink properly.
  195.     (let ((oldwin (selected-window))
  196.           (minheight 0)
  197.           (maxheight 0))
  198.       (save-excursion
  199.         (select-window (get-buffer-window (current-buffer)))
  200.         (setq minheight (if alreadythere
  201.                 (window-height)
  202.                   window-min-height))
  203.         (setq maxheight (/ (screen-height) 2))
  204.         (enlarge-window (- (min maxheight
  205.                     (max minheight
  206.                      (+ 2 (vertical-motion (point-max)))))
  207.                    (window-height)))
  208.         (goto-char (point-min))
  209.         (select-window oldwin))))))
  210.  
  211.  
  212. (defun c-macro-expansion (start end cppcommand &optional display)
  213.   "Run a preprocessor on region and return the output as a string.
  214. Expand the region between START and END in the current buffer using
  215. the shell command CPPCOMMAND (e.g. \"/lib/cpp -C -DDEBUG\").
  216. Be sure to use a -C (don't strip comments) or equivalent option.
  217. Optional arg DISPLAY non-nil means show messages in the echo area."
  218.  
  219. ;; Copy the current buffer's contents to a temporary hidden buffer.
  220. ;; Delete from END to end of buffer.  Insert a preprocessor #line
  221. ;; directive at START and after each #endif following START that are
  222. ;; not inside a comment or a string.  Put all the strings thus
  223. ;; inserted (without the "line" substring) in a list named linelist.
  224. ;; If START is inside a comment, prepend "*/" and append "/*" to the
  225. ;; #line directive.  If inside a string, prepend and append "\"".
  226. ;; Preprocess the buffer contents, then look for all the lines stored
  227. ;; in linelist starting from end of buffer.  The last line so found is
  228. ;; where START was, so return the substring from point to end of
  229. ;; buffer. 
  230.   (let ((inbuf (current-buffer))
  231.     (outbuf (get-buffer-create " *C Macro Expansion*"))
  232.     (filename (if (and buffer-file-name
  233.                (string-match (regexp-quote default-directory)
  234.                      buffer-file-name))
  235.               (substring buffer-file-name (match-end 0))
  236.             (buffer-name)))
  237.     (mymsg (format "Invoking %s%s%s on region..."
  238.                c-macro-preprocessor
  239.                (if (string= "" c-macro-cppflags) "" " ")
  240.                c-macro-cppflags))
  241.     (uniquestring "???!!!???!!! start of c-macro expansion ???!!!???!!!")
  242.     (startlinenum 0)
  243.     (linenum 0)
  244.     (startstat ())
  245.     (startmarker "")
  246.     (exit-status 0)
  247.     (tempname (make-temp-name "/tmp/")))
  248.     (unwind-protect
  249.     (save-excursion
  250.       (save-restriction
  251.         (widen)
  252.         (set-buffer outbuf)
  253.         (setq buffer-read-only nil)
  254.         (erase-buffer)
  255.         (set-syntax-table c-mode-syntax-table)
  256.         (insert-buffer-substring inbuf 1 end))
  257.  
  258.       ;; We have copied inbuf to outbuf.  Point is at end of
  259.       ;; outbuf.  Insert a space at the end, so cpp can correctly
  260.       ;; parse a token ending at END. 
  261.       (insert " ")
  262.  
  263.       ;; Save sexp status and line number at START.
  264.       (setq startstat (parse-partial-sexp 1 start))
  265.       (setq startlinenum (+ (count-lines 1 (point))
  266.                 (if (bolp) 1 0)))
  267.  
  268.       ;; Now we insert the #line directives after all #endif or
  269.       ;; #else following START going backward, so the lines we
  270.       ;; insert don't change the line numbers.
  271.       ;(switch-to-buffer outbuf) (debug)    ;debugging instructions
  272.       (goto-char (point-max))
  273.       (while (re-search-backward "\n#\\(endif\\|else\\)\\>" start 'move)
  274.         (if (equal (nthcdr 3 (parse-partial-sexp start (point)
  275.                              nil nil startstat))
  276.                '(nil nil nil 0 nil)) ;neither in string nor in
  277.                          ;comment nor after quote
  278.         (progn
  279.           (goto-char (match-end 0))
  280.           (setq linenum (+ startlinenum
  281.                    (count-lines start (point))))
  282.           (insert (format "\n#line %d \"%s\"\n" linenum filename))
  283.           (goto-char (match-beginning 0)))))
  284.  
  285.       ;; Now we are at START.  Insert the first #line directive.
  286.       ;; This must work even inside a string or comment, or after a
  287.       ;; quote.
  288.       (let* ((startinstring (nth 3 startstat))
  289.          (startincomment (nth 4 startstat))
  290.          (startafterquote (nth 5 startstat))
  291.          (startinbcomment (nth 7 startstat)))
  292.         (insert (if startafterquote " " "")
  293.             (cond (startinstring
  294.                (char-to-string startinstring))
  295.               (startincomment "*/")
  296.               (""))
  297.             (format "\n#line %d \"%s\"\n" startlinenum filename)
  298.             (setq startmarker
  299.               (concat uniquestring
  300.                   (cond (startinstring
  301.                      (char-to-string startinstring))
  302.                     (startincomment "/*")
  303.                     (startinbcomment "//"))
  304.                   (if startafterquote "\\")))))
  305.  
  306.       ;; Call the preprocessor.
  307.       (if display (message mymsg))
  308.       (setq exit-status
  309.         (call-process-region 1 (point-max) "sh" t t nil "-c"
  310.                      (concat cppcommand " 2>" tempname)))
  311.       (if display (message (concat mymsg "done")))
  312.       (if (= (buffer-size) 0)
  313.           ;; Empty output is normal after a fatal error.
  314.           (insert "\nPreprocessor produced no output\n")
  315.         ;; Find and delete the mark of the start of the expansion.
  316.         ;; Look for `# nn "file.c"' lines and delete them.
  317.         (goto-char (point-min))
  318.         (search-forward startmarker)
  319.         (delete-region 1 (point)))
  320.       (while (re-search-forward (concat "^# [0-9]+ \""
  321.                         (regexp-quote filename)
  322.                         "\"") nil t)
  323.         (beginning-of-line)
  324.         (let ((beg (point)))
  325.           (forward-line 1)
  326.           (delete-region beg (point))))
  327.  
  328.       ;; If CPP got errors, show them at the beginning.
  329.       (or (eq exit-status 0)
  330.           (progn
  331.         (goto-char (point-min))
  332.         (insert (format "Preprocessor terminated with status %s\n"
  333.                 exit-status))
  334.         (insert-file-contents tempname)
  335.         (insert "\n")))
  336.       (delete-file tempname)
  337.  
  338.       ;; Compute the return value, keeping in account the space
  339.       ;; inserted at the end of the buffer.
  340.       (buffer-substring 1 (max 1 (- (point-max) 1))))
  341.  
  342.       ;; Cleanup.
  343.       (kill-buffer outbuf))))
  344.  
  345. ;;; cmacexp.el ends here
  346.